package com.whfc.emp.redis.impl;

import com.alibaba.fastjson.JSON;
import com.whfc.common.util.JSONUtil;
import com.whfc.emp.dto.AppFaceGateDTO;
import com.whfc.emp.redis.FaceGateRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-08-16 15:27
 */
@Repository
public class FaceGateRedisDaoImpl implements FaceGateRedisDao {

    public static final String REDIS_KEY = "face-gate::%s";

    /**
     * 默认过期时间一周
     */
    public static final long TIMEOUT = 7 * 24 * 60;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void set(String deviceKey, AppFaceGateDTO faceGateDTO) {
        if (StringUtils.isBlank(deviceKey) || faceGateDTO == null) {
            return;
        }
        String key = String.format(REDIS_KEY, deviceKey);
        redisTemplate.opsForValue().set(key, JSONUtil.toString(faceGateDTO), TIMEOUT, TimeUnit.MINUTES);

    }

    @Override
    public AppFaceGateDTO get(String deviceKey) {
        if (StringUtils.isBlank(deviceKey)) {
            return null;
        }
        String key = String.format(REDIS_KEY, deviceKey);
        String faceGateStr = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(faceGateStr)) {
            return JSON.parseObject(faceGateStr, AppFaceGateDTO.class);
        }
        return null;
    }

    @Override
    public void del(String deviceKey) {
        if (StringUtils.isBlank(deviceKey)) {
            return;
        }
        String key = String.format(REDIS_KEY, deviceKey);
        redisTemplate.delete(key);
    }
}
